<?php

namespace App\Http\Controllers\Data;

use App\Http\Controllers\Controller;
use App\Models\News;
use Illuminate\Http\Request;
use Validator;


class NewsController extends Controller
{
    public function SampleNews()
    {
        $re = News::orderBy('time', 'desc')->paginate(3);
        $data = null;
        for ($i = 0; $i < sizeof($re); ++$i) {
            $data[$i]['cover_img'] = $re[$i]['cover_img'];
            $data[$i]['title'] = $re[$i]['title'];
            $data[$i]['content'] = $re[$i]['content'];
            $data[$i]['id'] = $re[$i]['id'];
            $data[$i]['time'] = $re[$i]['time'];
            $data[$i]['categories'] = $re[$i]['categories'];
        }
        $data=(['data'=>$data,'totalpage'=>$re->lastPage()]);

        return json_encode($data);

        // fake data

        // $data['img']='./news/00001.jpg';
        // $data['title']='声波传感器的应用';
        // $data['content']='超声波的工作原理，重要性能以及其他应用';
        // $data['id']='00001';
        // $data['time']='2019-7-25';
    }

    public function NextNewsInCategorie(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',
            'categories' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 401);
        }
        $data = News::where('id', '>', $request->id)->where(['categories' => $request->categories])->first();

        return json_encode($data);
    }

    public function NextNews(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 401);
        }
        $data =News::where('id', '>', $request->id)->first();
        if (!!$data) {
            return json_encode($data);
        } else {
            $data = ['success' => false, 'message' => '已经是最后一个！'];
            return json_encode($data);
        }

    }

    public function CompleteNews(News $news)
    {
        $re = News::where('id', '=', $news->id)
            ->first();

        $visits = $re['visits'];
        ++$visits;
        // var_dump($visits);
        News::where('id', '=', $news->id)->update(['visits' => $visits]);

        return json_encode($news);

        // fake data

        // $data['img']='./news/00001.jpg';
        // $data['title']='声波传感器的应用';
        // $data['content']='超声波的工作原理，重要性能以及其他应用';
        // $data['id']='00001';
        // $data['time']='2019-7-25';
        // $data['categories']='公司新闻'
        // $data['visits']=1;

        // return $data;
    }

    public function NewsCategorie(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'categories' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 401);
        }
        $data = null;
        $re = News::where('categories', $request->categories)->orderBy('time', 'desc')->paginate(3);
        if ($re) {
            for ($i = 0; $i < sizeof($re); ++$i) {
                $data[$i]['img'] = $re[$i]['img'];
                $data[$i]['title'] = $re[$i]['title'];
                $data[$i]['content'] = $re[$i]['content'];
                $data[$i]['id'] = $re[$i]['id'];
                $data[$i]['time'] = $re[$i]['time'];
                $data[$i]['categories'] = $re[$i]['categories'];
            }
            $data=(['data'=>$data,'totalpage'=>$re->lastPage()]);

            return json_encode($data);
        } else {
            session()->flash('false', '查找失败，无此类别！');
            $data = ['success' => false, 'message' => '无此类别'];
        }
    }

    public function NewsInsert(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|max:20',
            'content' => 'required|max:8000',
            'categories' => 'required',
            'cover_img' => 'required',
            'u_id' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 401);
        }

        $news = $request->all();
        $news['content'] = $request->content;
        $news['visits'] = 0;
        $news['time'] = date('Y-m-d h:i:s', time());
        unset($news['cover_img']);
        $res = News::create($news);

        $totalCoverImg = glob('./temp/'.$request->u_id.'/news/CoverImg'.'*');
        $CoverImgNumber = count($totalCoverImg);
        $CoverImg = $request->cover_img;
        if ($CoverImgNumber == 0) {
            $CoverImg = $request->cover_img;
        } else {
            $CoverImghandler = opendir('./temp/'.$request->u_id.'/news/CoverImg');
            while (($CoverImgname = readdir($CoverImghandler)) !== false) {
                if ($CoverImgname != '.' && $CoverImgname != '..') {
                    $temp = explode('.', $CoverImgname);
                    $extension = end($temp);
                    $picName = $res['id'].'.'.$extension;
                    $CoverImg = './news/CoverImg/'.$picName;
                    if (!file_exists($CoverImg)) {
                        $counter_file = $CoverImg;
                        $fopen = fopen($counter_file, 'wb '); //新建文件命令
                        fclose($fopen);
                    }
                    copy('./temp/'.$request->u_id.'/news/CoverImg/'.'cover_img'.'.'.$extension, $CoverImg);
                    News::where('id', '=', $res['id'])
                        ->update(['cover_img' => $CoverImg]);
                }
            }
        }
        $ContentImg = null;
        if (file_exists('./temp/'.$request->u_id.'/news/ContentImg')) {
            $totalContentImg = glob('./temp/'.$request->u_id.'/news/ContentImg'.'*');
            $ContentImgNumber = count($totalContentImg);
            if ($ContentImgNumber == 0) {
                $ContentImg = null;
            } else {
                $totalimgs = glob('./temp/'.$request->u_id.'/news/ContentImg/'.'*');
                $FileNumber = count($totalimgs);
                $ContentImghandler = opendir('./temp/'.$request->u_id.'/news/ContentImg');
                while (($ContentImgname = readdir($ContentImghandler)) !== false) {
                    if ($ContentImgname != '.' && $ContentImgname != '..') {
                        $temp = explode('.', $ContentImgname);
                        $extension = end($temp);
                        --$FileNumber;
                        $picName = $res['id'].'_'.$FileNumber.'.'.$extension;
                        $ContentImg = './news/ContentImg/'.$picName;
                        if (!file_exists($ContentImg)) {
                            $counter_file = $ContentImg;
                            $fopen = fopen($counter_file, 'wb '); //新建文件命令
                            fclose($fopen);
                        }
                        copy('./temp/'.$request->u_id.'/news/ContentImg/'.$ContentImgname, $ContentImg);
                    }
                }
            }
        }

        if (file_exists('./temp/'.$request->u_id.'/news/CoverImg')) {
            $dh = opendir('./temp/'.$request->u_id.'/news/CoverImg');
            while ($file = readdir($dh)) {
                if ($file != '.' && $file != '..') {
                    $fullpath = './temp/'.$request->u_id.'/news/CoverImg'.'/'.$file;
                    if (!is_dir($fullpath)) {
                        unlink($fullpath);
                    } else {
                        deldir($fullpath);
                    }
                }
            }
            closedir($dh);
        }
        if (file_exists('./temp/'.$request->u_id.'/news/ContentImg')) {
            $dh = opendir('./temp/'.$request->u_id.'/news/ContentImg');
            while ($file = readdir($dh)) {
                if ($file != '.' && $file != '..') {
                    $fullpath = './temp/'.$request->u_id.'/news/ContentImg'.'/'.$file;
                    if (!is_dir($fullpath)) {
                        unlink($fullpath);
                    } else {
                        deldir($fullpath);
                    }
                }
            }
            closedir($dh);
        }

        if ($res) {
            session()->flash('true', '新增成功！');
            $data = ['success' => true, 'message' => '新增成功'];

            return json_encode($data);
        } else {
            News::destroy($request->id);
            session()->flash('false', '新增失败!');

            return redirect()->back();
        }
    }

    public function NewsUpdate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|max:20',
            'categories' => 'required',
            'content' => 'required|max:8000',
            'id' => 'required',
            'u_id' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 401);
        }
        $news = $request->all();
        unset($news['u_id']);
        unset($news['id']);
        $original = News::where('id', '=', $request->id)->first();
        $compare['title'] = $original['title'];
        $compare['content'] = $original['content'];
        $compare['categories'] = $original['categories'];
        // if(isset($request->cover_img))
        // {
        //     $compare['cover_img'] = $original['cover_img'];
        // }
        if ($compare == $news) {
            $data = ['success' => false, 'message' => '修改的内容与原先内容相同！'];

            return json_encode($data);
        }
        if (isset($request->content_img)) {
            if (file_exists('./news/ContentImg')) {
                $dh = opendir('./news/ContentImg');

                while ($file = readdir($dh)) {
                    if ($file != '.' && $file != '..') {
                        $fullpath = './news/ContentImg'.'/'.$file;
                        $totalimgs = glob('./news/ContentImg/'.'*');
                        $FileNumber = count($totalimgs);
                        $temp = explode('.', $file);
                        $filename = $temp[0];
                        for ($i = 0; $i < $FileNumber; ++$i) {
                            if ($filename == $request->id.'_'.$i) {
                                if (!is_dir($fullpath)) {
                                    unlink($fullpath);
                                } else {
                                    deldir($fullpath);
                                }
                            }
                        }
                    }
                }
                closedir($dh);
            }
        }
        $ContentImg = null;
        if (file_exists('./temp/'.$request->u_id.'/news/ContentImg')) {
            $totalContentImg = glob('./temp/'.$request->u_id.'/news/ContentImg'.'*');
            $ContentImgNumber = count($totalContentImg);
            if ($ContentImgNumber == 0) {
                $ContentImg = null;
            } else {
                $ContentImghandler = opendir('./temp/'.$request->u_id.'/news/ContentImg');
                while (($ContentImgname = readdir($ContentImghandler)) !== false) {
                    if ($ContentImgname != '.' && $ContentImgname != '..') {
                        $temp = explode('.', $ContentImgname);
                        $extension = end($temp);
                        $picName = $request->id.'_'.$ContentImgNumber.'.'.$extension;
                        $ContentImg = './news/ContentImg/'.$picName;
                        if (!file_exists($ContentImg)) {
                            $counter_file = $ContentImg;
                            $fopen = fopen($counter_file, 'wb '); //新建文件命令
                            fclose($fopen);
                        }
                        copy('./temp/'.$request->u_id.'/news/ContentImg/'.$ContentImgname, $ContentImg);
                    }
                }
            }
        }

        $cover_del = News::where('id', '=', $request->id)->first();
        if (isset($request->cover_img)) {
            if (file_exists($cover_del['cover_img'])) {
                unlink($cover_del['cover_img']);
            }
        }
        $totalCoverImg = glob('./temp/'.$request->u_id.'/news/CoverImg'.'*');
        $CoverImgNumber = count($totalCoverImg);

        if ($CoverImgNumber != 0) {
            $CoverImghandle = opendir('./temp/'.$request->u_id.'/news/CoverImg');
            while (($CoverImgname = readdir($CoverImghandle)) !== false) {
                if ($CoverImgname != '.' && $CoverImgname != '..') {
                    $temp = explode('.', $CoverImgname);
                    $extension = end($temp);
                    $picName = 'cover_img'.'.'.$extension;
                    $CoverImg = './news/CoverImg/'.$request->id.'.'.$extension;

                    if (!file_exists($CoverImg)) {
                        $counter_file = $CoverImg;
                        $fopen = fopen($counter_file, 'wb '); //新建文件命令
                        fclose($fopen);
                    }
                    copy('./temp/'.$request->u_id.'/news/CoverImg/'.$picName, $CoverImg);
                    $news['cover_img'] = $CoverImg;
                }
            }
        }

        $re = News::where('id', $request->id)
            ->first();
        // var_dump($news);
        // exit;
        $re = News::where('id', '=', $request->id)->update($news);
        if (file_exists('./temp/'.$request->u_id.'/news/CoverImg')) {
            $dh = opendir('./temp/'.$request->u_id.'/news/CoverImg');
            while ($file = readdir($dh)) {
                if ($file != '.' && $file != '..') {
                    $fullpath = './temp/'.$request->u_id.'/news/CoverImg'.'/'.$file;
                    if (!is_dir($fullpath)) {
                        unlink($fullpath);
                    } else {
                        deldir($fullpath);
                    }
                }
            }
            closedir($dh);
        }
        if (file_exists('./temp/'.$request->u_id.'/news/ContentImg')) {
            $dh = opendir('./temp/'.$request->u_id.'/news/ContentImg');
            while ($file = readdir($dh)) {
                if ($file != '.' && $file != '..') {
                    $fullpath = './temp/'.$request->u_id.'/news/ContentImg'.'/'.$file;
                    if (!is_dir($fullpath)) {
                        unlink($fullpath);
                    } else {
                        deldir($fullpath);
                    }
                }
            }
            closedir($dh);
        }
        if ($re) {
            session()->flash('true', '修改成功！');
            $data = ['success' => true, 'message' => '修改成功'];

            return json_encode($data);
        } else {
            session()->flash('false', '修改失败,无对应id!');

            return redirect()->back();
        }
    }

    public function NewsDelete(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 401);
        }
        $res = News::where('id', '=', $request->id)->first();
        $re = News::where('id', '=', $request->id)->delete();
        if ($re) {
            if ((isset($res['cover_img']))) {
                if (file_exists($res['cover_img'])) {
                    unlink($res['cover_img']);
                }
            }
            if (file_exists('.\news\ContentImg')) {
                $handle = opendir('.\news\ContentImg');
                while ($file = readdir($handle)) {
                    if ($file != '.' && $file != '..') {
                        $fullpath = './news/ContentImg'.'/'.$file;
                        $totalimgs = glob('./news/ContentImg/'.'*');
                        $FileNumber = count($totalimgs);
                        $temp = explode('.', $file);
                        $filename = $temp[0];
                        for ($i = 0; $i < $FileNumber; ++$i) {
                            if ($filename == $res['id'].'_'.$i) {
                                if (!is_dir($fullpath)) {
                                    unlink($fullpath);
                                } else {
                                    deldir($fullpath);
                                }
                            }
                        }
                    }
                }
                closedir($handle);
            }
            session()->flash('ture', '删除成功!');
            $data = ['success' => true, 'message' => '删除成功!'];

            return json_encode($data);
        } else {
            session()->flash('false', '删除失败，无对应ID信息!');

            return redirect()->back();
        }
    }
}
